package com.achen.controller;

import com.achen.constant.MessageConstant;
import com.achen.entity.Result;
import com.achen.service.MemberService;
import com.achen.service.ReportService;
import com.achen.service.SetmealService;
import com.alibaba.dubbo.config.annotation.Reference;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author achen
 * @create 2020-04-26 14:36
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;

    //会员数量的折线图
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        HashMap<String, Object> map = null;
        try {
            map = new HashMap<>();
            //用于存取去年一年月份的集合
            List<String> monthList = new ArrayList<>();
            //获取calendar对象
            Calendar calendar = Calendar.getInstance();
            //计算过去一年的12个月（当前时间往前推12个月的时间）
            calendar.add(Calendar.MONTH, -12);
            for (int i = 0; i < 12; i++) {
                //从去年的当前月一个月一个月的加，加到今年的当前月
                calendar.add(Calendar.MONTH, 1);
                Date time = calendar.getTime(); //获取当前时间
                //将所有的月份添加到月份的集合中
                monthList.add(new SimpleDateFormat("yyyy.MM").format(time));
            }
            map.put("months", monthList);
            //查询每月分添加的会员的数量到集合中
            List<Integer> countList = memberService.findMemberCountByDate(monthList);
            map.put("memberCount", countList);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    //套餐百分比的饼形图
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        Map<String, Object> map = new HashMap<>();
        try {
            List<Map<String, Object>> countList = setmealService.findSetmealCountAndName();
            map.put("setmealCount", countList);

            List<String> nameList = new ArrayList<>();
            for (Map<String, Object> nameMap : countList) {
                String name = (String) nameMap.get("name");
                nameList.add(name);
            }
            map.put("setmealNames", nameList);

            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //运营统计数据
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据到excel模板中
    @RequestMapping("/exportBusinessReport")
    private Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) map.get("reportDate");
            Integer todayNewMember = (Integer) map.get("todayNewMember");
            Integer totalMember = (Integer) map.get("totalMember");
            Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");

            //获取模板excel文件的绝对路径
            String realPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //基于提供的excel模板文件在内存中创建一个excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(realPath)));
            //获取第一个sheet
            XSSFSheet sheet = excel.getSheetAt(0);

            //获取第三行第五列
            XSSFRow row = sheet.getRow(2);
            XSSFCell cell = row.getCell(5);
            //将报表日期输入到excel中，后面的同理这个往excel表格中输入
            cell.setCellValue(reportDate);
            //获取第五行第六列
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember); //将本日新增会员数添加至excel中
            row.getCell(7).setCellValue(totalMember); //总会员数
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember); //本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember); //本月新增会员数
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber); //今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber); //今日到诊数
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber); //本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber); //本周到诊数
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber); //本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber); //本月到诊数

            int rowNum = 12;
            for(Map m : hotSetmeal){//热门套餐
                String name = (String) m.get("name");
                Long setmeal_count = (Long) m.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) m.get("proportion");
                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //使用输出流进行表格下载，基于浏览器作为客户端进行下载
            OutputStream out = response.getOutputStream();
            //向浏览器声明输出的是excel文件类型
            response.setContentType("application/vnd.ms‐excel");
            //指定以附件的形式进行下载
            response.setHeader("Content-Disposition", "attachment;filename=report.xlsx");
            excel.write(out); //相应浏览器进行下载
            //关闭资源
            out.flush();
            out.close();
            excel.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据到pdf模板中
    @RequestMapping("/exportBusinessReportForPdf")
    private Result exportBusinessReportForPdf(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> map = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");
            //获取模板excel文件的绝对路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";
            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
            //填充数据---使用JavaBean数据源方式填充
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,map,new JRBeanCollectionDataSource(hotSetmeal));

            //使用输出流进行表格下载，基于浏览器作为客户端进行下载
            OutputStream out = response.getOutputStream();
            //向浏览器声明输出的是excel文件类型
            response.setContentType("application/vnd.ms‐pdf");
            //指定以附件的形式进行下载
            response.setHeader("Content-Disposition", "attachment;filename=report.pdf");
            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
            //关闭资源
            out.flush();
            out.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}